// 初始化 Three.js 场景
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });

// 将渲染器附加到容器
const container = document.getElementById('webgl-container');
if (container) {
    renderer.setSize(container.clientWidth, container.clientHeight);
    container.appendChild(renderer.domElement);
    camera.aspect = container.clientWidth / container.clientHeight;
    camera.updateProjectionMatrix();
} else {
    console.error('未找到webgl-container元素');
    document.body.appendChild(renderer.domElement);
    renderer.setSize(window.innerWidth, window.innerHeight);
}


// 添加光源
const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
directionalLight.position.set(5, 10, 7.5);
scene.add(directionalLight);

// 加载 GLB 模型
const loader = new THREE.GLTFLoader();
loader.load(
    'Model.glb', // 模型文件的路径
    function (gltf) {
        scene.add(gltf.scene);
        console.log('模型加载成功');
    },
    undefined, // onProgress 回调函数 (可选)
    function (error) {
        console.error('模型加载失败:', error);
    }
);

// 设置相机位置
camera.position.z = 5;

// 添加轨道控制器
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // 启用阻尼效果，使旋转更平滑
controls.dampingFactor = 0.05;
controls.screenSpacePanning = false;
controls.maxPolarAngle = Math.PI / 2;


// 动画循环
function animate() {
    requestAnimationFrame(animate);

    controls.update(); // 仅在启用阻尼或自动旋转时需要

    renderer.render(scene, camera);
}

// 处理窗口大小调整
function onWindowResize() {
    if (container) {
        camera.aspect = container.clientWidth / container.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(container.clientWidth, container.clientHeight);
    } else {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
    }
}
window.addEventListener('resize', onWindowResize, false);


animate();
